<template>
  <div class="menu-manage-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>菜单管理</span>
          <el-button type="primary" v-permission="'system:menu:add'" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            添加菜单
          </el-button>
        </div>
      </template>

      <el-table
        :data="menuList"
        border
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="menuName" label="菜单名称" width="200" />
        <el-table-column label="菜单类型" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.menuType === 1" type="primary">目录</el-tag>
            <el-tag v-else-if="row.menuType === 2" type="success">菜单</el-tag>
            <el-tag v-else type="info">按钮</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="icon" label="图标" width="100">
          <template #default="{ row }">
            <el-icon v-if="row.icon" :size="20">
              <component :is="row.icon" />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路由地址" width="180" />
        <el-table-column prop="component" label="组件路径" width="180" />
        <el-table-column prop="permission" label="权限标识" width="200" />
        <el-table-column prop="orderNum" label="排序" width="80" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              v-permission="'system:menu:edit'"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              v-permission="'system:menu:delete'"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑菜单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      @close="resetForm"
    >
      <el-form
        ref="menuFormRef"
        :model="menuForm"
        :rules="menuRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="父菜单" prop="parentId">
              <el-tree-select
                v-model="menuForm.parentId"
                :data="parentMenuOptions"
                :props="{ children: 'children', label: 'menuName', value: 'id' }"
                placeholder="选择父菜单"
                check-strictly
                :render-after-expand="false"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单类型" prop="menuType">
              <el-radio-group v-model="menuForm.menuType">
                <el-radio :label="1">目录</el-radio>
                <el-radio :label="2">菜单</el-radio>
                <el-radio :label="3">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="menuName">
              <el-input v-model="menuForm.menuName" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="menuForm.orderNum" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="menuForm.menuType !== 3">
          <el-col :span="12">
            <el-form-item label="路由地址" prop="path">
              <el-input v-model="menuForm.path" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组件路径" prop="component">
              <el-input v-model="menuForm.component" placeholder="请输入组件路径" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="权限标识" prop="permission">
              <el-input v-model="menuForm.permission" placeholder="如：system:user:list" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单图标" prop="icon">
              <el-select v-model="menuForm.icon" placeholder="选择图标" clearable filterable style="width: 100%">
                <el-option
                  v-for="icon in iconList"
                  :key="icon"
                  :label="icon"
                  :value="icon"
                >
                  <div style="display: flex; align-items: center;">
                    <el-icon :size="16" style="margin-right: 8px">
                      <component :is="icon" />
                    </el-icon>
                    <span>{{ icon }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="显示状态" prop="visible">
              <el-radio-group v-model="menuForm.visible">
                <el-radio :label="1">显示</el-radio>
                <el-radio :label="0">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单状态" prop="status">
              <el-radio-group v-model="menuForm.status">
                <el-radio :label="1">正常</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { getAllMenuTree, addMenu, updateMenu, deleteMenu } from '@/api/menu'
import { ElMessage, ElMessageBox } from 'element-plus'

const loading = ref(false)
const menuList = ref([])

const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const submitLoading = ref(false)
const menuFormRef = ref(null)

// Element Plus 常用图标列表
const iconList = [
  'HomeFilled', 'User', 'UserFilled', 'Setting', 'Menu', 'Document', 
  'Folder', 'FolderOpened', 'Files', 'List', 'Grid', 'Management',
  'Tools', 'Monitor', 'DataAnalysis', 'PieChart', 'TrendCharts',
  'Message', 'ChatLineSquare', 'Bell', 'Phone', 'Postcard',
  'Lock', 'Unlock', 'Key', 'View', 'Hide', 'Search',
  'Plus', 'Minus', 'Delete', 'Edit', 'Check', 'Close',
  'RefreshLeft', 'RefreshRight', 'Upload', 'Download', 'Share',
  'Calendar', 'Clock', 'Timer', 'AlarmClock', 'Connection',
  'ShoppingCart', 'Goods', 'Present', 'Box', 'Tickets',
  'Position', 'Location', 'MapLocation', 'Guide', 'Compass',
  'Star', 'StarFilled', 'Picture', 'PictureFilled', 'Camera'
]

const menuForm = reactive({
  id: null,
  parentId: 0,
  menuName: '',
  menuType: 2,
  path: '',
  component: '',
  permission: '',
  icon: '',
  orderNum: 0,
  visible: 1,
  status: 1
})

const menuRules = {
  parentId: [
    { required: true, message: '请选择父菜单', trigger: 'change' }
  ],
  menuName: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { max: 50, message: '菜单名称长度不能超过50个字符', trigger: 'blur' }
  ],
  menuType: [
    { required: true, message: '请选择菜单类型', trigger: 'change' }
  ],
  orderNum: [
    { required: true, message: '请输入显示排序', trigger: 'blur' }
  ]
}

// 父菜单选项（添加顶级选项）
const parentMenuOptions = computed(() => {
  const options = [
    {
      id: 0,
      menuName: '顶级菜单',
      children: menuList.value
    }
  ]
  return options
})

// 加载菜单树
const loadMenuTree = async () => {
  loading.value = true
  try {
    const res = await getAllMenuTree()
    if (res.code === 200) {
      menuList.value = res.data
    }
  } catch (error) {
    console.error('加载菜单树失败:', error)
  } finally {
    loading.value = false
  }
}

// 添加菜单
const handleAdd = () => {
  dialogTitle.value = '添加菜单'
  isEdit.value = false
  dialogVisible.value = true
}

// 编辑菜单
const handleEdit = (row) => {
  dialogTitle.value = '编辑菜单'
  isEdit.value = true
  menuForm.id = row.id
  menuForm.parentId = row.parentId
  menuForm.menuName = row.menuName
  menuForm.menuType = row.menuType
  menuForm.path = row.path
  menuForm.component = row.component
  menuForm.permission = row.permission
  menuForm.icon = row.icon
  menuForm.orderNum = row.orderNum
  menuForm.visible = row.visible
  menuForm.status = row.status
  dialogVisible.value = true
}

// 删除菜单
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除菜单"${row.menuName}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteMenu(row.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        loadMenuTree()
      }
    } catch (error) {
      console.error('删除菜单失败:', error)
    }
  }).catch(() => {
    // 取消删除
  })
}

// 提交表单
const submitForm = async () => {
  if (!menuFormRef.value) return

  await menuFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const data = {
          ...menuForm
        }
        
        let res
        if (isEdit.value) {
          res = await updateMenu(data)
        } else {
          res = await addMenu(data)
        }

        if (res.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
          dialogVisible.value = false
          loadMenuTree()
        }
      } catch (error) {
        console.error('操作失败:', error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  menuForm.id = null
  menuForm.parentId = 0
  menuForm.menuName = ''
  menuForm.menuType = 2
  menuForm.path = ''
  menuForm.component = ''
  menuForm.permission = ''
  menuForm.icon = ''
  menuForm.orderNum = 0
  menuForm.visible = 1
  menuForm.status = 1
  
  if (menuFormRef.value) {
    menuFormRef.value.resetFields()
  }
}

onMounted(() => {
  loadMenuTree()
})
</script>

<style scoped>
.menu-manage-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>